// templates/templates.js
Page({
  data: {
    activeTemplateId: null,
    scrollHeight: 500, // 初始高度
    templates: [
      {
        id: 1,
        name: "学术经典",
        description: "适合学术申请、科研岗位",
        preview: "/images/工作城市.png",
        component: "academicTemplate"
      },
      {
        id: 2,
        name: "现代简约",
        description: "通用型设计，适配多种场景",
        preview: "/images/蓝白色极简大气风求职简历.png",
        component: "modernTemplate"
      },
      {
        id: 3,
        name: "创意设计",
        description: "艺术类、设计类岗位适用",
        preview: "/images/蓝白色极简大气风求职简历.png",
        component: "creativeTemplate"
      }
    ]
  },

  onReady() {
    this.calculateScrollHeight();
  },

  calculateScrollHeight() {
    const systemInfo = wx.getSystemInfoSync();
    const query = this.createSelectorQuery();
    
    query.select('.page-title').boundingClientRect();
    query.select('.action-bar').boundingClientRect();
    query.exec(res => {
      const titleHeight = res[0].height;
      const barHeight = res[1].height;
      const padding = 20; // 上下padding总和
      
      this.setData({
        scrollHeight: systemInfo.windowHeight - titleHeight - barHeight - padding
      });
    });
  },

  handleSelectTemplate(e) {
    const templateId = e.currentTarget.dataset.id;
    this.setData({
      activeTemplateId: templateId === this.data.activeTemplateId ? null : templateId
    });
  },

  handleConfirm() {
    if (!this.data.activeTemplateId) {
      wx.showToast({
        title: '请先选择模板',
        icon: 'none'
      });
      return;
    }

    const selectedTemplate = this.data.templates.find(
      t => t.id === this.data.activeTemplateId
    );

    const app = getApp();
    const resumeData = app.globalData.resumeData || {};

    wx.navigateTo({
      url: `/pages/preview/preview`,
      success: (res) => {
        res.eventChannel.emit('sendTemplateData', {
          template: selectedTemplate,
          formData: resumeData
        });
      }
    });
  },

  onShow() {
    const app = getApp();
    if (app.globalData.selectedTemplateId) {
      this.setData({
        activeTemplateId: app.globalData.selectedTemplateId
      });
    }
  }
});